import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:s_utils/s_utils.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebPage extends StatefulWidget {
  const WebPage({
    Key? key,
    required this.url,
    this.title = "",
    this.showAppBar = true,
    this.hasStatusBar = true,
    this.onNavigationRequest,
    this.resizeToAvoidBottomInset = true,
  }) : super(key: key);

  final String url;
  final String title;
  final bool showAppBar;
  final bool hasStatusBar;
  final bool resizeToAvoidBottomInset;
  final ValueChanged? onNavigationRequest;

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  final WebViewController controller = WebViewController();
  int progress = 0;
  bool showProgress = true;
  late String title;

  @override
  void initState() {
    title = widget.title;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      initWeb();
    });
    super.initState();
  }

  initWeb() async {
    logger.w("Open web url: ${widget.url}");
    if (await canLaunchUrlString(widget.url)) {
      Future.delayed(.4.seconds, () {
        controller
          ..loadRequest(Uri.parse(widget.url))
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageFinished: (url) {
                Future.delayed(.4.seconds, () {
                  if (widget.title == "") {
                    controller.getTitle().then((v) {
                      title = v ?? '';
                      if(mounted) setState(() {});
                    });
                  }
                  if(mounted) setState(() => showProgress = false);
                });
              },
              onProgress: (v) {
                if(mounted) setState(() => progress = v);
              },
              onNavigationRequest: (NavigationRequest request) {
                if (widget.onNavigationRequest != null) {
                  widget.onNavigationRequest!(request.url);
                }
                return NavigationDecision.navigate;
              },
            ),
          );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Get.theme;
    return Scaffold(
      resizeToAvoidBottomInset: widget.resizeToAvoidBottomInset,
      appBar: widget.showAppBar
          ? PreferredSize(
              preferredSize: Size.fromHeight(164.r),
              child: AppBar(
                title: Text(title),
                centerTitle: false,
                titleSpacing: 0,
                leading: ExpandTap(
                  onTap: Get.back,
                  child: Center(
                    child: Icon(
                      const IconData(0xf060, fontFamily: "faSolidIcon"),
                      color: Colors.black,
                      size: 62.r,
                    ),
                  ),
                ),
              ),
            )
          : null,
      body: Stack(
        children: [
          WebViewWidget(
            controller: controller,
          ),
          if (showProgress)
            AnimatedContainer(
              duration: 200.milliseconds,
              width: Sizes.screenWidth / 100 * progress,
              height: 15.r,
              color: theme.colorScheme.secondary,
            ),
          if (!widget.showAppBar)
            Positioned(
              top: Sizes.statusBarHeight > 50
                  ? (widget.hasStatusBar ? Sizes.statusBarHeight : 0)
                  : (widget.hasStatusBar ? Sizes.statusBarHeight : 0) + 50.r,
              right: 50.r,
              child: GestureDetector(
                onTap: Get.back,
                child: Container(
                  width: 120.r,
                  height: 120.r,
                  padding: EdgeInsets.all(10.r),
                  decoration: BoxDecoration(
                    color: theme.colorScheme.surfaceBright,
                    borderRadius: BorderRadius.circular(80.r),
                  ),
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: theme.colorScheme.primary.withValues(alpha: .2),
                      borderRadius: BorderRadius.circular(80.r),
                    ),
                    child: Icon(
                      const IconData(0xf00d, fontFamily: "faSolidIcon"),
                      size: 50.r,
                      color: theme.colorScheme.primary,
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}
